#!/bin/bash
set -euo pipefail  # 遇到错误立即退出，防止无效执行

# Cloudflare临时域名保持脚本
# 在系统重启后执行，保持临时域名的稳定性

echo "🔄 Cloudflare临时域名保持工具"
echo "=================================="

# 配置变量 - 集中管理路径，便于未来修改
PROJECT_DIR="/home/root1/pythonApp"
CACHE_FILE="${PROJECT_DIR}/current_domain_cache.txt"
TUNNEL_SERVICE="tunnel"
APP_SERVICE="chatapp"

# 进入项目目录
cd "$PROJECT_DIR" || {
    echo "❌ 无法进入项目目录: $PROJECT_DIR"
    exit 1
}

# 函数：检查并确保隧道服务运行
ensure_tunnel_running() {
    echo "🔍 检查隧道状态..."
    local container_id
    container_id=$(docker compose ps -q "$TUNNEL_SERVICE" 2>/dev/null)
    
    if [ -z "$container_id" ]; then
        echo "⚠️  隧道容器不存在，启动隧道服务..."
        docker compose up -d "$TUNNEL_SERVICE"
        return $?
    fi
    
    local status
    status=$(docker inspect -f '{{.State.Status}}' "$container_id" 2>/dev/null)
    if [ "$status" != "running" ]; then
        echo "⚠️  隧道已停止，重启隧道服务..."
        docker compose restart "$TUNNEL_SERVICE"
        return $?
    fi
    
    echo "✅ 隧道正在运行"
    return 0
}

# 函数：获取当前隧道域名，带重试机制
get_current_domain() {
    local max_attempts=10
    local attempt=1
    local domain=""
    
    echo "📍 获取隧道域名（最多尝试$max_attempts次）..."
    
    while [ $attempt -le $max_attempts ]; do
        domain=$(docker compose logs "$TUNNEL_SERVICE" 2>/dev/null | 
                 grep -Eo "https://[a-zA-Z0-9-]+\.trycloudflare\.com" | 
                 tail -1)
        
        if [ -n "$domain" ]; then
            echo "✅ 成功获取域名: $domain"
            echo "$domain"
            return 0
        fi
        
        echo "⏳ 第$attempt次尝试失败，等待2秒后重试..."
        attempt=$((attempt + 1))
        sleep 2
    done
    
    echo "❌ 超过最大尝试次数，无法获取域名"
    return 1
}

# 函数：更新配置文件中的域名
update_configs() {
    local new_domain=$1
    echo "🔄 更新配置文件以使用新域名: $new_domain"
    
    # 更新.env文件
    if grep -q "^CORS_ALLOWED_ORIGINS=" "$PROJECT_DIR/.env"; then
        sed -i "s|^CORS_ALLOWED_ORIGINS=.*|CORS_ALLOWED_ORIGINS=$new_domain|" "$PROJECT_DIR/.env"
    else
        echo "CORS_ALLOWED_ORIGINS=$new_domain" >> "$PROJECT_DIR/.env"
    fi
    
    # 更新前端文件
    for file in "register.html" "index.html"; do
        local html_path="${PROJECT_DIR}/static/${file}"
        if [ -f "$html_path" ]; then
            sed -i "s|const API_BASE_URL = '.*';|const API_BASE_URL = '$new_domain';|g" "$html_path"
        else
            echo "⚠️  前端文件不存在: $html_path"
        fi
    done
    
    # 更新app.py中的CORS配置
    local app_py="${PROJECT_DIR}/app.py"
    if [ -f "$app_py" ]; then
        sed -i "s|cors_allowed_origins=\[\"https://.*\.trycloudflare\.com\"\]|cors_allowed_origins=\[\"$new_domain\"\]|g" "$app_py"
    else
        echo "⚠️  app.py文件不存在: $app_py"
    fi
}

# 函数：等待应用服务就绪
wait_for_app() {
    local domain=$1
    local max_attempts=10
    local attempt=1
    
    echo "⏳ 等待应用服务就绪..."
    while [ $attempt -le $max_attempts ]; do
        local status
        status=$(curl -s -o /dev/null -w "%{http_code}" "${domain}/api/health" 2>/dev/null)
        if [ "$status" -eq 200 ]; then
            echo "✅ 应用服务已就绪"
            return 0
        fi
        attempt=$((attempt + 1))
        sleep 2
    done
    
    echo "⚠️  应用服务未在预期时间内就绪"
    return 1
}

# 主逻辑
if [ -f "$CACHE_FILE" ]; then
    echo "✅ 发现域名缓存文件: $CACHE_FILE"
    CACHED_DOMAIN=$(cat "$CACHE_FILE")
    echo "📋 缓存的域名: $CACHED_DOMAIN"
    
    # 确保隧道运行
    ensure_tunnel_running || {
        echo "❌ 隧道启动失败，无法继续"
        exit 1
    }
    
    # 获取当前域名
    CURRENT_DOMAIN=$(get_current_domain) || {
        echo "❌ 获取域名失败，终止操作"
        exit 1
    }
    
    # 比较域名是否变化
    if [ "$CACHED_DOMAIN" != "$CURRENT_DOMAIN" ]; then
        echo "🔄 检测到域名已变化: $CACHED_DOMAIN → $CURRENT_DOMAIN"
        
        # 更新配置
        update_configs "$CURRENT_DOMAIN"
        
        # 重启应用服务
        echo "🔄 重启应用服务以应用新配置..."
        docker compose restart "$APP_SERVICE"
        
        # 更新缓存
        echo "$CURRENT_DOMAIN" > "$CACHE_FILE"
        echo "💾 域名缓存已更新"
        
        # 等待应用就绪并测试
        wait_for_app "$CURRENT_DOMAIN"
        echo "🧪 健康检查状态码: $(curl -s -o /dev/null -w "%{http_code}" "${CURRENT_DOMAIN}/api/health" 2>/dev/null || echo "错误")"
    else
        echo "✅ 域名未变化，配置保持一致"
    fi
else
    echo "⚠️  未找到域名缓存文件，创建初始缓存..."
    
    # 确保隧道运行
    ensure_tunnel_running || {
        echo "❌ 隧道启动失败，无法继续"
        exit 1
    }
    
    # 获取当前域名
    CURRENT_DOMAIN=$(get_current_domain) || {
        echo "❌ 获取域名失败，终止操作"
        exit 1
    }
    
    # 创建缓存并更新配置
    echo "$CURRENT_DOMAIN" > "$CACHE_FILE"
    echo "💾 初始域名缓存已创建"
    
    update_configs "$CURRENT_DOMAIN"
    
    # 重启应用服务
    echo "🔄 重启应用服务以应用配置..."
    docker compose restart "$APP_SERVICE"
    
    # 等待应用就绪
    wait_for_app "$CURRENT_DOMAIN"
fi

echo "✅ 临时域名保持任务完成"
